package lowijs.XfireClient.packet;

import lowijs.XfDroid.FriendDBAdapter;
import lowijs.XfDroid.XfDroidConstants;
import lowijs.XfireClient.IM;
import lowijs.XfireClient.event.EventManager;
import lowijs.XfireClient.event.ReceiveImEvent;
import lowijs.XfireClient.util.Util;
import android.util.Log;

public class ReceiveMessagePacket extends Packet {
	public static final int MSGTYPE_IM = 0x00;
	public static final int MSGTYPE_ACKNOWLEDGEMENT = 0x01;
	public static final int MSGTYPE_CHATAUTH = 0x02;
	public static final int MSGTYPE_TYPING = 0x03;

	private byte[] sid = new byte[16];
	private byte peermsg;
	private int msgtype;
	private int imindex;

	public ReceiveMessagePacket(byte[] data) {
		System.arraycopy(data, 8, sid, 0, 16);
		peermsg = data[35];
		msgtype = Util.intFromBytes(data, 43, 4);
		
		switch(msgtype) {
		case MSGTYPE_IM: // we have to ack this, so save some data
			if (peermsg == 0x02) {// we just sent an IM, no need to ack the ack
				Log.d(XfDroidConstants.LOG_TAG, FriendDBAdapter.toString(sid) + ": Confirmation from server");
			} else {
				imindex = Util.intFromBytes(data, 56, 4);
				byte[] imbytes = new byte[fromLowHigh(data[64], data[65])];
				System.arraycopy(data, 66, imbytes, 0, imbytes.length);
				String message = new String(imbytes);

				Log.d(XfDroidConstants.LOG_TAG, FriendDBAdapter.toString(sid) + ": Message recieved on " + message);
				FriendDBAdapter db = FriendDBAdapter.getInstance(null);
				IM im = db.postMessage(sid, message, imindex);
				EventManager.fireEvent(new ReceiveImEvent(im));
			}

			break;
		case MSGTYPE_CHATAUTH: // we have to ack this?
			Log.d(XfDroidConstants.LOG_TAG, FriendDBAdapter.toString(sid) + ": Autherize?");
			break;
		case MSGTYPE_TYPING:
			Log.d(XfDroidConstants.LOG_TAG, FriendDBAdapter.toString(sid) + ": User typing");
			break;
		case MSGTYPE_ACKNOWLEDGEMENT: // we have to ack this, so save some data
			imindex = Util.intFromBytes(data, 56, 4);
			Log.d(XfDroidConstants.LOG_TAG, FriendDBAdapter.toString(sid) + ": Confirmation from server " + imindex);
			break;
		default:
			Log.d(XfDroidConstants.LOG_TAG, FriendDBAdapter.toString(sid) + ": Don't know type " + msgtype);
			break;
		}
	}
	
	public byte[] getSid() {
		return sid;
	}
	
	public int getMessageType() {
		return msgtype;
	}
	
	public int getImIndex() {
		return imindex;
	}
}
